﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.Roles;
using B.S.Meeting.ReadAPI.Dtos;
using CSRedis;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.Roles
{
    public class SelectRoleCommandHandler : IRequestHandler<SelectRoleCommand, APIResult<IList<Role>>>
    {
        /// <summary>
        /// 实现Redis接口
        /// </summary>
        //CSRedisClient redisClient;
        IBaseRepository<Role> rRep;
        IMapper mapper;
        ILogger<SelectRoleCommandHandler> logger;
        /// <summary>
        /// 调用封装好的Redis获取列表接口
        /// </summary>
        IRedisGetList<Role> rRedis;
        public SelectRoleCommandHandler(IBaseRepository<Role> rRep, IMapper mapper, ILogger<SelectRoleCommandHandler> logger/*, CSRedisClient redisClient*/, IRedisGetList<Role> rRedis)
        {
            this.rRep = rRep;
            this.mapper = mapper;
            this.logger = logger;
            this.rRedis = rRedis;
            //this.redisClient = redisClient;
        }
        public async Task<APIResult<IList<Role>>> Handle(SelectRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ////从Redis中获取角色列表
                //var redisrole= await redisClient.GetAsync<IList<Role>>("RoleList");
                //if (redisrole != null && redisrole.Count > 0)
                //{
                //    return new APIResult<IList<Role>>
                //    {
                //        Code = StatusEnumCode.Ok,
                //        Message = "获取角色列表成功",
                //        Data = redisrole
                //    };
                //}
                ////如果Redis中没有数据，则从数据库中获取
                //else
                //{
                //    logger.LogInformation("Redis中没有角色列表数据，正在从数据库中获取角色列表数据");
                //    var role = rRep.GetAll().Where(x => x.IsDel == false).ToList();
                //    redisrole = list;
                //    //将获取到的角色列表存入Redis中，设置过期时间为30分钟
                //    var setResult = await redisClient.SetAsync("RoleList", redisrole, TimeSpan.FromMinutes(30));
                //}
                IList<Role> rolelist = await rRedis.GetList("GetRoleList", async () =>
                {
                    var role = await rRep.GetAll().Where(x => x.IsDel == false).ToListAsync();
                    return role;
                }, 60 * 60);
                return new APIResult<IList<Role>>
                    {
                    Code = StatusEnumCode.Ok,
                    Message = "获取角色列表成功",
                    Data = rolelist
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
